/**
 * 设备管理相关云函数
 */
var AV = require('leanengine')
var Community = require('../models/Community')
var Device = require('../models/Device')
var Property = require('../models/Property')


// 社区搜索
AV.Cloud.define('community_search', function(request, response) {
    var searchKey = request.params.searchKey
    Community.community_search(searchKey,function(data){
        response.success(data)
    })
})

// 获取物业名称
AV.Cloud.define('property_getName',function(request,response) {
    var propertyId = request.params.id
    Property.property_communityIn(propertyId,function(data){
        response.success(data)
    })
})

// 获取社区详情
AV.Cloud.define('community_detail',function(request,response) {
    var communityId = request.params.communityId
    Community.community_details(communityId,function(data){
        response.success(data)
    })
})

// 根据社区ID获取设备列表
AV.Cloud.define('community_deviceList',function(request,response) {
    var communityId = request.params.communityId
    Device.device_list(communityId,function(data){
        response.success(data)
    });
})

// 新增设备
AV.Cloud.define('device_add', function(request, response) {
    var position = request.params.position
    var communityId = request.params.communityId
    if(position != undefined && communityId != undefined){
        Device.device_new(position,communityId,function(data) {
            response.success(data)
        })
    }else{
        response.success('')
    }

})

// 删除设备
AV.Cloud.define('device_del', function(request, response) {
    var deviceId = request.params.deviceId
    if(deviceId != ''){
        Device.device_del(deviceId,function(data) {
            if(data != ''){
                response.success(1)
            }
        })
    }

})

// 批量删除
AV.Cloud.define('device_del_more',function(request,response) {
    var deviceList = request.params
    console.log(deviceList)
    if(deviceList != ''){
        var query = new AV.Query('Device')
        query.containedIn('objectId',deviceList)
        query.find().then(function(results) {
            query.destroyAll().then(function() {
              // 删除成功
              response.success(1)
            }, function() {
              // 失败
              response.success(0)
            });
        }, function(error) {
        })
    }else{
        response.success(0)
    }
})
